import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.*;
import org.apache.tika.Tika;

public class Extractor {
  public static void main(String[] args) {
  }

  public static boolean searchContent(File file, String searchTerm) throws Exception {
    Tika tika = new Tika();
    BufferedReader inp = null;
    PrintWriter out = null;

    String inFName = file.getCanonicalPath();
    String fName = file.getName().toLowerCase();

    boolean flagFound = false;

    try {
      inp = new BufferedReader(tika.parse(new File(inFName)));

      String line;
      while ((line = inp.readLine()) != null) {
        StringTokenizer tokens = new StringTokenizer(line);
        while (tokens.hasMoreTokens()) {
          String token = tokens.nextToken();
          if (token.toLowerCase().equals(searchTerm.toLowerCase())) {
            flagFound = true;
          }
        }
      }
    } finally {
      if (inp != null) {
        inp.close();
      }
    }
    return flagFound;
  }

  public static void getContent(File file) throws Exception {
    Tika tika = new Tika();
    //String text = tika.parseToString(new File(file));
    BufferedReader inputStream = null;
    PrintWriter outputStream = null;

    String inFName = file.getCanonicalPath();
    String fName = file.getName().toLowerCase();
    String outFName = "output\\" + fName.replace(".pdf", ".txt");

    try {
      inputStream = new BufferedReader(tika.parse(new File(inFName)));
      outputStream = new PrintWriter(new FileWriter(outFName));

      String line;
      int lineCtr = 0;
      int lenStr = 0;
      while ((line = inputStream.readLine()) != null) {
        outputStream.println(line);
        lenStr += line.length();
        lineCtr++;
      }
      System.out.println("\t>> DEBUG: " + outFName + ": " + lenStr);
      System.out.println("\t>> DEBUG: " + lineCtr + " lines were saved.");
    }
    finally {
      if (inputStream != null) {
        inputStream.close();
      }
    }
    //System.out.print(text);
  }
}

